#include <iostream>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <cstdlib>

using namespace std;

// 父进程 -- 读取
// 子进程 -- 写入

int main()
{
    // 1. 创建管道
    int fds[2] = {0};
    int n = pipe(fds); // fds: 输出型参数
    if (n != 0)
    {
        std::cerr << "pipe error" << std::endl;
        return 1;
    }

    // 2. 创建子进程
    pid_t id = fork();
    if (id < 0)
    {
        cerr << "fork error" << endl;
        return 2;
    }
    else if (id == 0)
    {
        // 子进程
        // 3. 关闭不需要的 fd, 关闭 read
        int cnt = 0;
        int total = 0;
        while (true)
        {
            close(fds[0]);

            string message = "h";
            // string message = "hello IsLand1314, hello ";
            // message += to_string(getpid());
            // message += ", ";
            // message += to_string(cnt);

            // fds[1]
            total += ::write(fds[1], message.c_str(), message.size());
            cnt++;
            cout << "total: " << total << endl; // 最后写到 65536 个字节
            sleep(2);

            // break; // 写端关闭
        }

        exit(0);
    }
    else
    {
        // 父进程
        // 3. 关闭不需要的 fd, 关闭 write
        close(fds[1]);
        
        char buffer[1024];
        while(true)
        {
            sleep(1);
            ssize_t n = ::read(fds[0], buffer, 1024);
            //ssize_t n = ::read(fds[0], buffer, 5);
            if(n > 0)
            {
                buffer[n] = 0;
                cout << "chile->father, message: " << buffer << endl;
            }
            else if(n == 0)
            {
                 // 如果写端关闭
                //读端读完管道内部数据，再读取就会读取到返回值 0
                //表示对端关闭，也表示读到文件结尾
                cout << "n: " << n << endl;
                cout << "child quit??? me too " << endl;
                break;
            }
            close(fds[0]);
            break;
            cout << endl;
        }

        // pid_t rid = waitpid(id, nullptr, 0);
        // cout << "father wait chile success" << rid << endl;

        // 记录退出信息
        int status = 0;
        pid_t rid = waitpid(id, &status, 0);
        cout << "father wait chile success: " << rid << " exit code: " << 
        ((status<<8)&0xFF) << ", exit sig: " << (status & 0x7F) << endl;
    }

    return 0;
}